package com.adminsystem.java.excelFile.service.impl;

import com.adminsystem.java.common.PageResult;
import com.adminsystem.java.common.Result;
import com.adminsystem.java.excelFile.mapper.StudentScoreMapper;
import com.adminsystem.java.excelFile.pojo.entity.StudentScore;
import com.adminsystem.java.excelFile.pojo.param.StudentScorePageParam;
import com.adminsystem.java.excelFile.pojo.vo.StudentScoreVO;
import com.adminsystem.java.excelFile.service.StudentScoreService;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangpeiao
 */
@Slf4j
@Service
public class StudentScoreServiceImpl implements StudentScoreService {

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    @Override
    public PageResult<StudentScoreVO> queryByPage(StudentScorePageParam param) {
        log.info("开始分页查询学生成绩，参数: {}", param);

        // 开始分页
        PageHelper.startPage(param.getPageNum(), param.getPageSize());

        // 查询数据
        List<StudentScore> scores = studentScoreMapper.selectByCondition(
                param.getClassName(),
                param.getGender()
        );

        // 转换为 VO
        List<StudentScoreVO> vos = scores.stream()
                .map(score -> {
                    StudentScoreVO vo = new StudentScoreVO();
                    BeanUtils.copyProperties(score,vo); // 注意顺序
                    return vo;
                })
                .collect(Collectors.toList());

        // 获取分页信息
        PageInfo<StudentScore> pageInfo = new PageInfo<>(scores);

        // 构建返回结果
        PageResult<StudentScoreVO> result = new PageResult<>();
        result.setList(vos);
        result.setTotal(pageInfo.getTotal());
        result.setPageNum(param.getPageNum());
        result.setPageSize(param.getPageSize());
        result.setTotalPages((int) Math.ceil((double) pageInfo.getTotal() / param.getPageSize()));

        log.info("分页查询完成，共 {} 条记录", pageInfo.getTotal());
        return result;
    }

    @Override
    public List<StudentScoreVO> exportAll(StudentScorePageParam param) {
        log.info("导出所有学生成绩，参数: {}", param);

        // 查询所有符合条件的数据（不分页）
        List<StudentScore> scores = studentScoreMapper.selectByCondition(
                param.getClassName(),
                param.getGender()
        );

        // 转换为 VO
        return scores.stream()
                .map(score -> {
                    StudentScoreVO vo = new StudentScoreVO();
                    BeanUtils.copyProperties(score, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Result<String> importExcel(MultipartFile file) {
        studentScoreMapper.truncateTable();
        try {
            List<StudentScoreVO> dataList = EasyExcel.read(file.getInputStream())
                    .head(StudentScoreVO.class)
                    .sheet()
                    .headRowNumber(4)
                    .doReadSync();

            if (dataList == null || dataList.isEmpty()) {
                return Result.fail("导入数据为空");
            }

            // 转换 VO -> Entity
            List<StudentScore> entities = dataList.stream()
                    .map(vo -> {
                        StudentScore entity = new StudentScore();
                        BeanUtils.copyProperties(vo, entity);
                        return entity;
                    })
                    .collect(Collectors.toList());

            // 批量插入数据库
            int rows = studentScoreMapper.batchInsert(entities);

            if (rows > 0) {
                return Result.success("成功导入 " + entities.size() + " 条数据");
            } else {
                return Result.fail("导入失败，请检查数据格式");
            }

        } catch (Exception e) {
            return Result.fail("导入失败");
        }
    }


}
